<?php
define('BME_INSERTION',true);
require_once("../core/Base.php");

$Bme=new BME_Base();
$Bme->__constructor();

$file=$argv[1];
if(!file_exists($file)) $Bme->error("I can't find the file $file");
$dataset=$argv[2];
if(!$dataset) $Bme->error("Please tell me the dataset");
$gene=$argv[3];
if(!$gene) $Bme->error("Please tell me the gene name");
$verbose=$argv[4]=='mute'?false:true;

if($verbose) echo "Preparing files and directories\n";
is_dir($Bme->tmp_path) or $Bme->error("I can't find the tmp dir ".$Bme->tmp_path);
$outdir=$Bme->tmp_path."/analysis/uploadSequences";
$out="$outdir/".basename($file);
passthru("rm -Rf '$outdir' 2>&1 || read ");
passthru("mkdir -p '$outdir' 2>&1 || read ");
copy($file,$out) or $Bme->error("I can't copy $file into $out");
if($verbose) echo "Exec'ing seqretsplit\n";
passthru("seqretsplit '$out' '$outdir/o.fasta' -osdirectory2 '$outdir' -osformat2 'fasta' 2>/dev/null || (echo 'Error on seqretsplit' && read ) ");
unlink($out) or $Bme->error("I can't delete $out");

if($verbose) echo "Uploading sequences\n";
$Bme->openDB();
foreach(scandir($outdir) as $fasta){
	if($verbose) echo "\rReading $fasta...                     ";
	if($fasta=='.'||$fasta=='..') continue;
	$cont=file($outdir."/".$fasta);
	$def=substr(array_shift($cont),1);
	$seq=str_replace(array("\n","\r",""),"",join("",$cont));
	$Bme->DBquery("insert into `Sequence`(`idSequence`,`version`,`source`,`Dataset_idDataset`,`description`,`sequence`,`gen`)
	values('',0,'primary','".$Bme->DBescape($dataset)."','".$Bme->DBescape($def)."','".$Bme->DBescape($seq)."','".$Bme->DBescape($gene)."')");
}
$Bme->closeDB();
if($verbose) echo "\nDone.\n";

?>
